﻿using Dapper.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using YouWei.Api.Common;
using YouWei.Api.Models;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Enums;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace YouWei.Api.Controllers
{
    /// <summary>
    /// 直播控制器
    /// </summary>
    public class LiveController : BaseApiController
    {
        string pushUrl = ConfigHelper.GetAppSettingValue("pushUrl");
        string apikey = ConfigHelper.GetAppSettingValue("pushKey");
        string pullUrl = ConfigHelper.GetAppSettingValue("pullUrl");

        string FileUploadUrl = ConfigHelper.GetAppSettingValue("FileUploadUrl");
        private LiveRoomService _liveRoom = new LiveRoomService();
        private LiveConcernService _liveConcern = new LiveConcernService();

        /// <summary>
        /// 推送地址
        /// rtmp://bizid+直播码+防盗链签名+地址有效期
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultData<string> PushUrl(LiveModel model)
        {
            //直播码 
            //也叫房间号，推荐用随机数字或者用户 ID，注意一个合法的直播码需要拼接 BIZID 前缀。
            string home = pushUrl.Substring(0, pushUrl.IndexOf('.')) + "_" + model.RoomId;
            string txTime = GetTxTime();
            string txSecret = GetTxSecret(apikey, home, txTime);
            string url = string.Format("rtmp://{0}/{1}?txSecret={2}&txTime={3}", pushUrl, home, txSecret, txTime);
            return ResultData<string>.Success(url, "ok");
        }

        /// <summary>
        /// 播放地址
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<string> PullUrl(LiveModel model)
        {
            string home = pushUrl.Substring(0, pushUrl.IndexOf('.')) + "_" + model.RoomId;
            string txTime = GetTxTime();
            string txSecret = GetTxSecret(apikey, home, txTime);
            string url = string.Format("{0}/{1}.flv?txSecret={2}&txTime={3}", pullUrl, home, txSecret, txTime);
            return ResultData<string>.Success(url, "ok");
        }

        /// <summary>
        /// 获取签名IM
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<string> GenSig(string user)
        {
            string imSDKAppID = ConfigHelper.GetAppSettingValue("imSDKAppID");
            string imKey = ConfigHelper.GetAppSettingValue("imKey");
            TLSSigAPIv2 tLS = new TLSSigAPIv2(EConvert.ToInt(imSDKAppID), imKey);
            return ResultData<string>.Success(tLS.GenSig(user), "ok");
        }

        /// <summary>
        ///何时该 URL 会过期，格式是十六进制的 UNIX 时间戳，比如 5867D600 代表 2017 年 1 月 1 日 0 时 0 点 0 分过期，
        ///我们的客户一般会将 txTime 设置为当前时间 24 小时以后过期
        /// </summary>
        /// <returns></returns>
        private string GetTxTime()
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

            long ss = Convert.ToInt64((DateTime.Now.AddHours(10) - startTime).TotalSeconds);
            return String.Format("{0:X}", ss);
        }

        /// <summary>
        /// 获取密钥
        /// </summary>
        /// <param name="key"></param>
        /// <param name="home"></param>
        /// <param name="txTime"></param>
        /// <returns></returns>
        private string GetTxSecret(string key, string home, string txTime)
        {
            return MD5Helper.MD5String(key + home + txTime);
        }

        /// <summary>
        /// 查询直播室列表
        /// </summary>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <param name="playerUserId">观看用户ID</param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<Page<LiveRoom>> GetLiveList(int PageSize, int PageIndex, int playerUserId)
        {
            ResultData<Page<LiveRoom>> rData = ResultData<Page<LiveRoom>>.Error("未查询到内容信息");
            try
            {
                ReqLiveRoomCondition condition = new ReqLiveRoomCondition();
                condition.PlayerUserID = playerUserId;
                Page<LiveRoom> list = _liveRoom.GetPages(PageIndex, PageSize, condition);
                foreach (var item in list.rows)
                {
                    item.CoverImage = string.Format("{0}/{1}", FileUploadUrl, item.CoverImage);
                    if (!item.WeChartUserHead.StartsWith("https://"))
                    {

                        item.WeChartUserHead = string.Format("{0}/{1}", FileUploadUrl, item.WeChartUserHead);
                    }
                }
                rData = ResultData<Page<LiveRoom>>.Success(list);

            }
            catch (Exception ex)
            {
                rData.message = ex.Message;
            }

            return rData;
        }

        /// <summary>
        /// 添加直播室
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultData<LiveRoom> AddLiveRoom(LiveRoom room)
        {
            room.CreatedTime = DateTime.Now;
            room.IsActive = 1;
            room.StartTime = DateTime.Now;
            room.UpdatedTime = DefultTime;
            room.Status = 0;
            room.CoverImage = room.CoverImage.Replace(FileUploadUrl, "").Replace("/", "");
            room.PusherUrl = PushUrl(new LiveModel()
            {
                UserId = room.UserID,
                RoomId = room.UserID
            }).data;
            room.PlayerUrl = PullUrl(new LiveModel()
            {
                UserId = room.UserID,
                RoomId = room.UserID
            }).data;
            var id = _liveRoom.Insert(room);
            room.RoomID = EConvert.ToInt(id);
            return ResultData<LiveRoom>.Success(room);
        }

        /// <summary>
        /// 添加直播室关注
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultData<bool> AddLiveRoomConcern(LiveRoomConcernModel model)
        {
            ResultData<bool> rData = ResultData<bool>.Error("操作失败");
            if (model.PlayerUserID < 1)
            {
                rData.message = "观看用户ID为空";
                return rData;
            }
            if (model.PusherUserID < 1)
            {
                rData.message = "主播用户ID为空";
                return rData;
            }
            try
            {
                if (!_liveConcern.IsExistUserRoomConcern(model.PlayerUserID, model.PusherUserID))
                {
                    LiveConcern info = new LiveConcern
                    {
                        CancelTime = DateTime.MinValue,
                        CreatedTime = DateTime.Now,
                        IsActive = 1,
                        PlayerUserID = model.PlayerUserID,
                        PusherUserID = model.PusherUserID
                    };
                    _liveConcern.Insert(info);
                    rData = ResultData<bool>.Success(true);
                }
                else
                {
                    rData.message = "用户已关注";
                }
            }
            catch (Exception ex)
            {
                rData.message = ex.Message;
            }
            return rData;
        }

        /// <summary>
        /// 取消直播室关注
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultData<bool> CancelLiveRoomConcern(LiveRoomConcernModel model)
        {
            ResultData<bool> rData = ResultData<bool>.Error("操作失败");
            if (model.PlayerUserID < 1)
            {
                rData.message = "观看用户ID为空";
                return rData;
            }
            if (model.PusherUserID < 1)
            {
                rData.message = "主播用户ID为空";
                return rData;
            }
            try
            {
                LiveConcern info = _liveConcern.GetUserRoomConcernInfo(model.PlayerUserID, model.PusherUserID);
                if (info != null)
                {
                    info.CancelTime = DateTime.Now;
                    info.IsActive = 0;
                    _liveConcern.Update(info);
                    rData = ResultData<bool>.Success(true);
                }
                else
                {
                    rData.message = "信息不存在";
                }
            }
            catch (Exception ex)
            {
                rData.message = ex.Message;
            }
            return rData;
        }

        /// <summary>
        /// 根据用户ID获取最后一次直播室信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ResultData<LiveRoom> GetLastLive(int userId)
        {
            ResultData<LiveRoom> rData = ResultData<LiveRoom>.Error("没有找到数据");
            try
            {
                var obj = _liveRoom.GetLastLiveRoomByUserId(userId);
                if (obj!=null)
                {
                    obj.CoverImage = string.Format("{0}/{1}", FileUploadUrl, obj.CoverImage);
                    if (!obj.WeChartUserHead.StartsWith("https://"))
                    {

                        obj.WeChartUserHead = string.Format("{0}/{1}", FileUploadUrl, obj.WeChartUserHead);
                    }
                }               
                rData = ResultData<LiveRoom>.Success(obj);                
            }
            catch (Exception ex)
            {
                rData.message = ex.Message;
            }
            return rData;
        }

        /// <summary>
        /// 更新直播室状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<LiveRoom> UpdateStatusForLiveRoom(UpdateLiveRoomStatusModel model)
        {
            ResultData<LiveRoom> rData = ResultData<LiveRoom>.Error("操作失败");
            if (model.RoomId < 1)
            {
                rData.message = "直播室ID为空";
                return rData;
            }
            if (model.Stauts < 1)
            {
                rData.message = "状态ID为空";
                return rData;
            }
            if (!Enum.IsDefined(typeof(LiveRoomStatus), model.Stauts))
            {
                rData.message = "非法状态";
                return rData;
            }
            try
            {
                var obj = _liveRoom.SingleOrDefault(model.RoomId);
                if (obj == null)
                {
                    rData.message = "非法操作,找不到数据";
                }
                else
                {
                    if (_liveRoom.UpdateStatusForLiveRoom(model.RoomId, model.Stauts))
                    {
                        rData = ResultData<LiveRoom>.Success(obj);
                    }                  
                }                
            }
            catch (Exception ex)
            {
                rData.message = ex.Message;
            }
            return rData;
        }
    }
}
